package com.greyshark.lib.bluetooth.core.internal

import android.content.Context
import android.media.MediaPlayer
import com.greyshark.lib.bluetooth.R

internal class BackgroundMusicPlayer {

    companion object {
        val instance: BackgroundMusicPlayer by lazy(
            mode = LazyThreadSafetyMode.SYNCHRONIZED
        ) {
            BackgroundMusicPlayer()
        }
    }

    private var isEnable = true
    private var interval = 5000L

    private var player: MediaPlayer? = null

    fun run(context: Context) {
        if (!isEnable) {
            pauseMusic()
            return
        }
        try {
            pauseMusic()
            player = MediaPlayer.create(context, R.raw.silence)
            player?.apply {
                setVolume(0f, 0f)
                setOnCompletionListener { mediaPlayer: MediaPlayer? ->
                    Thread.sleep(interval)
                    playMusic()
                }
                setOnErrorListener { mp: MediaPlayer?, what: Int, extra: Int ->
                    false
                }
            }
            playMusic()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun playMusic() {
        if (!isEnable) {
            return
        }
        try {
            if (player?.isPlaying == true) {
                player?.start()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun pauseMusic() {
        if (!isEnable) {
            return
        }
        try {
            player?.let {
                it.stop()
                it.release()
            }
            player = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}